from rest_framework import generics, status
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import filters
from common.response import APIResponse
from .models import SSHSession, SSHCommand
from .serializers import SSHSessionSerializer, SSHCommandSerializer


class SSHSessionListView(generics.ListAPIView):
    """SSH会话列表视图"""
    serializer_class = SSHSessionSerializer
    permission_classes = [IsAuthenticated]
    filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter]
    filterset_fields = ['status', 'host']
    search_fields = ['host__hostname', 'host__ip']
    ordering_fields = ['start_time', 'end_time']
    ordering = ['-start_time']

    def get_queryset(self):
        """获取当前用户的SSH会话"""
        return SSHSession.objects.filter(user=self.request.user)


class SSHCommandHistoryView(generics.ListAPIView):
    """SSH命令历史视图"""
    serializer_class = SSHCommandSerializer
    permission_classes = [IsAuthenticated]
    filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter]
    search_fields = ['command']
    ordering_fields = ['start_time']
    ordering = ['-start_time']

    def get_queryset(self):
        """获取指定会话的命令历史"""
        session_id = self.kwargs['session_id']
        return SSHCommand.objects.filter(
            session_id=session_id,
            session__user=self.request.user
        )
